/* 
 * File:   CreateIndex.cpp
 * Author: vikrantsingh
 * 
 * Created on 30 November, 2013, 10:56 PM
 */

#include "CreateIndex.h"
#include "../dependency/debug.h"
#include "../dependency/StatusCodes.h"
#include "../Sysfiles/SysCatalog.h"
#include "../PageLayout/Tuple.h"
#include "../IndexManager/BPlusTree.h"
#include "../IndexManager/IndexUtil.h"
#include "TableScan.h"
#include "../dependency/util.h"

CreateIndex::CreateIndex() {
}

CreateIndex::CreateIndex(const CreateIndex& orig) {
}

CreateIndex::~CreateIndex() {
}

STATUS_CODE CreateIndex::run(QueryStructures *queryStruct) {

    DEBUG("Entering create index ");
    if (isDBOpen == false)
        return DATABASE_NOT_OPEN;

    int indexHeaderPageNum = -1;

    SysCatalog sysCatalog;
    int err = sysCatalog.addIndexEntry(queryStruct, indexHeaderPageNum);
    if (err != SUCCESS)
        return err;
    DEBUG("Exiting create index ");

    /*
     *  ADD TO INDEX ALL PREVIOUS TABLE;
     */
    SysCatalog cat;
    Schema schema;


    err = cat.getSchema(queryStruct->tableName.c_str(), schema);
    DEBUG("tableName=" << schema.tableName.c_str());
    if (err == TABLE_NOT_FOUND) {
        return err;
    }

    Heap heapFile(schema.tableName.c_str());
    TableScan tableScan(&heapFile);




    IndexHeaderPage indexHeaderPage(indexHeaderPageNum);
    //            cout<<"INSERT INTO INDEX HEADER PAGE NUM"<<indexHeaderPageNum<<endl;

    int keySize = indexHeaderPage.getKeySize();

    char *keyData = new char[keySize];
    vector<int> colIds;
    for (unsigned l = 0; l < queryStruct->indexColumnNames.size(); l++) {
        colIds.push_back(schema.getColumnNum(queryStruct->indexColumnNames[l]));
    }


    //            cout<<"INSERT INTO INDEX HEADER PAGE NUM"<<indexHeaderPageNum<<endl;
    BPlusTree bplusTree(indexHeaderPageNum);


    char *record;
    unsigned recordLen;
    int count = 0;
    DEBUG("starting table scan");
    while (tableScan.getNextRec(record, recordLen) != SCAN_OVER) {
        Tuple tuple(schema, record, recordLen);
        //no where conditions
        //add all to resultset
        DEBUG("to delete rows=" << tuple.toString());
        RIDStruct rid = tableScan.getRid();
        tuple.getKeyData(colIds, keyData);
//        cout << "keyData:" << IndexUtil::keyToString(keyData, &indexHeaderPage) << endl;
        bplusTree.insert(keyData, rid);

        count++;


    }

    return SUCCESS;
}
